package com.xuef.security.browser;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by moveb on 2018/5/5.
 * 自定义登录成功后跳转方式
 */
@Component("blogAuthenticationSucHandler")
public class BlogAuthenticationSucHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(BlogAuthenticationSucHandler.class);

    @Autowired
    private ObjectMapper objectMapper;

    // 登录成功后会被调用
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        RequestCache requestCache = new HttpSessionRequestCache();
        SavedRequest savedRequest = requestCache.getRequest(httpServletRequest, httpServletResponse);

        // 将跳转路径修改为登录者的博客相应页
        String targetUrl = "";
        if(savedRequest != null){
            targetUrl = savedRequest.getRedirectUrl();
            targetUrl = targetUrl.replaceAll("nil", authentication.getName());
            logger.info("\n ------------替换后的url: " + targetUrl);
        }else{
            // ??? 注销后，savedRequest为空?产生了怪异的跳转
            // 注销后再登录，就跳转到博客首页
            targetUrl = "/blogs";
        }

        // 如果是异步登录，就返回Json

        // 否则，调用父类的处理方法
        //super.onAuthenticationSuccess(httpServletRequest, httpServletResponse, authentication);
        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, targetUrl);
    }
}
